import 'package:flutter/services.dart';
import 'package:flutter_admin/pages/common/cry/cry.dart';
import 'package:flutter_admin/pages/common/cry/cry_all.dart';
import 'package:flutter_admin/pages/common/cry/vo/select_option_vo.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter/material.dart';
import 'package:flutter_admin/pages/common/cry/cry_button.dart';
import 'package:flutter_admin/api/odoo/dynamic_data_api.dart';
import 'package:flutter_admin/api/odoo/udt_tb_workreportrecord_odoo_api.dart';
import 'package:flutter_admin/pages/common/cry/model/response_body_api.dart';
import 'package:flutter_admin/models/odoo/udt_tb_workreportrecord.dart';
import 'package:flutter_admin/pages/common/cry/utils/cry_utils.dart';
import 'package:flutter_admin/utils/adaptive_util.dart';
import 'package:flutter_admin/utils/eventbus.dart';
import 'package:flutter_admin/utils/store_util.dart';
import 'package:permission_handler/permission_handler.dart';
import '../../../generated/l10n.dart';
import 'package:qrscan/qrscan.dart' as scanner;


class UdtTbWorkreportrecordEdit extends StatefulWidget {
  UdtTbWorkreportrecordEdit({this.udtTbWorkreportrecord});

  final UdtTbWorkreportrecord? udtTbWorkreportrecord;

  @override
  _UdtTbWorkreportrecordEditState createState() =>
      _UdtTbWorkreportrecordEditState();
}

class _UdtTbWorkreportrecordEditState extends State<UdtTbWorkreportrecordEdit> {
  late UdtTbWorkreportrecord udtTbWorkreportrecord;
  bool? isAdd;

  late var _subscription;

  final GlobalKey<FormState> formKey = GlobalKey<FormState>();

  late List<SelectOptionVO> shiftList = [];

  late List<SelectOptionVO> reportworkerList = [];

  late bool isLoading;

  bool check = false;

  @override
  void initState() {
    super.initState();
    this.isLoading = isDisplayDesktop(Cry.context) ? false : true;
    // this.isLoading = false;
    this.isAdd = widget.udtTbWorkreportrecord == null;
    _subscription = EventBus.getSubscriber()
        .where((event) => event["key"] == "workreportrecordEdit")
        .listen(_onEnvent);
    this.udtTbWorkreportrecord =
        widget.udtTbWorkreportrecord ?? UdtTbWorkreportrecord();
    this.check = this.udtTbWorkreportrecord.repairStatus == "1"?true:false;
    _loadSelectVO();
  }

  @override
  void dispose() {
    StoreUtil.write("key", "workreportrecord");
    _subscription.cancel();
    super.dispose();
  }

  //处理扫码后的结果
  void _onEnvent(dynamic obj) async {
    ResponseBodyApi res = await DynamicDataApi.getModels(
        model: "res.users", key: 'login', val: obj["scan"]);
    if (res.success!) {
      if (res.data.length == 0) {
        CryUtils.message("该人员不存在");
        return;
      } else if (res.data.length > 1) {
        CryUtils.message("编号重复");
        return;
      } else {
        if (udtTbWorkreportrecord.reportworkerId !=
            res.data[0]["id"].toString()) {
          CryUtils.message("您没有修改权限");
          setState(() {});
          return;
        }
        isLoading = false;
        setState(() {});
      }
    }
  }

  _loadSelectVO() async {
    shiftList = await DynamicDataApi.getModelSelect(
        model: 'base.shift', name: 'shiftname');
    // todo 获取该工位下的所有人员
    ResponseBodyApi resUser = await DynamicDataApi.getModels(
        model: "base.teamuser",
        key: "team_id",
        val: int.parse(udtTbWorkreportrecord.teamId!));
    if (resUser.success!) {
      reportworkerList = [];
      for (int i = 0; i < resUser.data.length; i++) {
        reportworkerList.add(SelectOptionVO(
            value: resUser.data[i]["staff_id"][0].toString(),
            label: resUser.data[i]["staff_id"][1].toString()));
      }
    }
    setState(() {});
  }

  Future _scan() async {
    await Permission.camera.request();
    String? barcode = await scanner.scan();
    if (barcode == null) {
      return;
    }
    _onEnvent({"scan":barcode});
  }

  List<Widget> _formList(){
    List<Widget> list = [
      CryInput(
        label: '生产单号',
        value: udtTbWorkreportrecord.productionorderno,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.productionorderno = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      Text('')
          :CryInput(
        label: '产品图号',
        value: udtTbWorkreportrecord.productCode,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.productCode = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '产品名称',
        value: udtTbWorkreportrecord.productName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.productName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      CryInput(
        label: '规格型号',
        value: udtTbWorkreportrecord.spec,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.spec = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      )
          :CryInput(
        label: '材料型号',
        value: udtTbWorkreportrecord.spec,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.spec = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      Text('')
          :CryInput(
        label: '生产工厂',
        value: udtTbWorkreportrecord.factoryName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.factoryName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '生产车间',
        value: udtTbWorkreportrecord.workshopName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.workshopName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '生产工序',
        value: udtTbWorkreportrecord.processName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.processName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '设备工位',
        value: udtTbWorkreportrecord.stationName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.stationName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CryInput(
        label: '班组',
        value: udtTbWorkreportrecord.teamName,
        enable: false,
        onSaved: (v) {
          udtTbWorkreportrecord.teamName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      isDisplayDesktop(context)
          ? CrySelect(
        label: '报工人名称',
        dataList: reportworkerList,
        value: udtTbWorkreportrecord.reportworkerId,
        onSaved: (v) {
          udtTbWorkreportrecord.reportworkerId = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      )
          : CryInput(
        label: '报工人名称',
        enable: false,
        value: udtTbWorkreportrecord.reportworkerName,
        onSaved: (v) {
          udtTbWorkreportrecord.reportworkerName = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      CrySelect(
        label: '班次',
        value: udtTbWorkreportrecord.shiftId,
        dataList: shiftList,
        onSaved: (v) {
          udtTbWorkreportrecord.shiftId = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      new CheckboxListTile(
        // secondary: const Icon(Icons.production_quantity_limits),
        title: const Text('是否为返修产品'),

        value: this.check,
        onChanged: (bool? value) {
          // setState(() {
          //   this.check = !this.check;
          // });
        },
      ):Text(''),
      !isDisplayDesktop(context)&&check?Text(''):CryInputNum(
        label: '合格数量',
        value: udtTbWorkreportrecord.qualifiedquantity,
        onSaved: (v) {
          udtTbWorkreportrecord.qualifiedquantity = v;
        },
        validator: (v) {
          return double.parse(v!) == 0 ? "合格数量不能为0" : null;
        },
      ),
      !isDisplayDesktop(context)&&check?Text(''):CryInputNum(
        label: '不合格数量',
        value: udtTbWorkreportrecord.unqualifiedquantity,
        onSaved: (v) {
          udtTbWorkreportrecord.unqualifiedquantity = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      check?CryInputNum(
          label: '返修数量',
          value: udtTbWorkreportrecord.repairquantity,
          onSaved: (v) {
            udtTbWorkreportrecord.repairquantity = v;
          },
          validator: (v) {
            return double.parse(v!) == 0 ? "返修数量不能为0" : null;
          },
        ):Text(''):CryInputNum(
        label: '备货数量',
        value: udtTbWorkreportrecord.repairquantity,
        onSaved: (v) {
          udtTbWorkreportrecord.repairquantity = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      Text('')
          :CryInputNum(
        label: '刀数',
        value: udtTbWorkreportrecord.cutting,
        onSaved: (v) {
          udtTbWorkreportrecord.cutting = v;
        },
        validator: (v) {
          return v!.isEmpty ? S.of(context).required : null;
        },
      ),
      !isDisplayDesktop(context) && StoreUtil.read("type") != 0?
      Text('')
          :CryInputNum(
        label: '换模个数',
        value: udtTbWorkreportrecord.replacenumber,
        onSaved: (v) {
          udtTbWorkreportrecord.replacenumber = v;
        },
      ),
      CryInput(
        label: '备注',
        value: udtTbWorkreportrecord.remark,
        onSaved: (v) {
          udtTbWorkreportrecord.remark = v;
        },
      ),
    ];

    return list;
  }

  @override
  Widget build(BuildContext context) {
    var form = Form(
      key: formKey,
      child: Wrap(
        children: _formList(),
      ),
    );

    var buttonBar = ButtonBar(
      alignment: MainAxisAlignment.center,
      children: <Widget>[
        CryButton(
          label: S.of(context).save,
          onPressed: () {
            if (isLoading) {
              CryUtils.message("请扫描报工人");
              return;
            }
            FormState form = formKey.currentState!;
            if (!form.validate()) {
              return;
            }
            form.save();
            UdtTbWorkreportrecordOdooApi.saveOrUpdate(
                    udtTbWorkreportrecord.toOdooMap())
                .then((ResponseBodyApi res) {
              if (!res.success!) {
                // CryUtils.message(res.message!);
                return;
              }
              Navigator.pop(context, true);
              CryUtils.message(S.of(context).saved);
            });
          },
          iconData: Icons.save,
        ),
        CryButton(
          label: S.of(context).cancel,
          onPressed: () {
            Navigator.pop(context);
          },
          iconData: Icons.cancel,
        )
      ],
    );
    var result = Scaffold(
      appBar: AppBar(
        title: Text(this.isAdd! ? S.of(context).add : S.of(context).modify),
        // actions: [
        //   CryButton(
        //     label: "扫码",
        //     onPressed: () {
        //       _scan();
        //     },
        //     iconData: Icons.qr_code_scanner_outlined,
        //   )
        // ],
      ),

      body: Stack(
        alignment: Alignment.center,
        fit: StackFit.expand, //未定位widget占满Stack整个空间
        children: <Widget>[
          // Positioned(
          //   left: 18.0,
          //   child: Text("I am Jack"),
          // ),
          SingleChildScrollView(
            child: form,
          ),
          isLoading
              ? Positioned(
                  // top: 18.0,
                  child: Container(
                    width: 650,
                    height: 650,
                    color: Colors.black87,
                    child: Center(
                      child: Text(
                        "请扫描报工人",
                        style: TextStyle(fontSize: 36, color: Colors.red),
                      ),
                    ),
                  ),
                )
              : Container(),
        ],
      ),
      // SingleChildScrollView(
      //   child: Column(
      //     children: [
      //       form],
      //   ),
      // ),
      bottomNavigationBar: buttonBar,
    );
    return SizedBox(
      width: 650,
      height: 650,
      child: result,
    );
    // return result;
  }
}
